<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: songaimin@clcw.com.cn  Blog:http://blog.csdn.net/samxx8        |
// +------------------------------------------------------------------------+
//
namespace AuctionCore\CarDealer;

use AuctionCore\AntNest\UserCenter;
use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\Common\PhpRedis;
use AuctionCore\Other\CouponLog;
use AuctionCore\Other\Address;
use AuctionCore\System\AuctionException;
use \AuctionCore\Common\PhpMemcache;

/**
 * 车商帐户功能类
 *
 * @author       Administrator
 */
class  Dealer
{

    /**
     * 车商id
     *
     * @var      int
     */
    private $dealer_id;

    /**
     * 构造,初始化"车商id"
     *
     * @param    int $dealer_id 车商id
     *
     * @return   void
     */
    public function __construct($dealer_id)
    {
        $this->dealer_id = $dealer_id;
    }

    /**
     *开通车商登录网站
     *
     * @param array info [用户名，密码,昵称,密保手机号,短信手机号]
     *
     * @return user_id
     */
    public function enable_front_user($info)
    {
        if (is_numeric($info['user_name']) && (strlen($info['user_name']) == 11)) {
            $info['user_name'] = 'du' . $info['user_name'];
        }
        $user_id = \AuctionCore\Account\FrontUser::create($info);
        if (intval($user_id) > 0) {
            $dealer_user = M('dealer_user');
            $dealer_user_info = array(
                'uid' => $user_id
            , 'dealer_id' => $this->dealer_id
            , 'status' => 1
            );
            $ok = $dealer_user->add($dealer_user_info);
            if ($ok) {
                $fu = new \AuctionCore\Account\FrontUser($user_id);
                $fu->set_group(2);//帐号加车商组,组id为1
                return $user_id;
            }
        }
        return false;
    }


    /**
     * 车商基本详细
     *
     * @return   Object
     */
    public function dealer_base_info()
    {
        $map = array('d.dealer_id' => array('eq', $this->dealer_id));
        $fields = 'd.*,u.uid,u.real_name,u.user_name,u.avatar,u.sex,e.emp_id as manager_id,e.real_name manager_name';
        $prefix = C('DB_PREFIX');
        $row = M('car_dealer')->alias('d')->field($fields)
            ->join("LEFT JOIN {$prefix}dealer_user as du ON du.dealer_id=d.dealer_id")
            ->join("LEFT JOIN {$prefix}user as u ON du.uid=u.uid")
            ->join("LEFT JOIN {$prefix}dealer_manager as dm ON d.dealer_id=dm.dealer_id")
            ->join("LEFT JOIN {$prefix}employee e ON dm.emp_id=e.emp_id")
            ->where($map)->find();
        return $row;
    }

    /**
     * 车商基本信息
     *
     * @return array
     */
    public function baseInfo()
    {
        $map = ['d.dealer_id' => $this->dealer_id];
        $fields = 'd.*,du.uid,dm.emp_id as manager_id,e.real_name as manager_name';
        $prefix = C('DB_PREFIX');
        $row = M('car_dealer')->alias('d')->field($fields)
            ->join("INNER JOIN {$prefix}dealer_user as du ON du.dealer_id=d.dealer_id")
            ->join("LEFT JOIN {$prefix}dealer_manager as dm ON d.dealer_id=dm.dealer_id")
            ->join("LEFT JOIN {$prefix}employee e ON dm.emp_id=e.emp_id")
            ->where($map)->find();
        $uc = new UserCenter();
        $userInfo = $uc->info($row['uid'], 2);
        if (!empty($userInfo)) {
            $row['uid'] = $userInfo['account_id'];
            $row['real_name'] = $userInfo['real_name'];
            $row['user_name'] = $userInfo['account_name'];
            $row['avatar'] = $userInfo['account_avatar'];
            $row['sex'] = $userInfo['sex'];
            $row['mobile'] = $userInfo['mobile'];
            $row['contact_mobile'] = $userInfo['mobile'];
        }
        $row['level_name'] = C('DEALER_LEVEL')[$row['level']];
        $row['auth_type_name'] = C('DEALER_CERTIFY_TYPE')[$row['auth_type']];
        $addr = new Address();
        if (!empty($row['province']) || !empty($row['city']) || !empty($row['area']) || !empty($row['address'])) {
            $province = $addr->get_name_by_code($row['province']);
            $city = $addr->get_name_by_code($row['city']);
            $area = $addr->get_name_by_code($row['area']);
            $row['address'] = $province . " " . $city . " " . $area . " " . $row['address'];
        } else {
            $row['address'] = '无';
        }
        if (!empty($row['business_city'])) {
            if ($row['business_city'] == 200) {
                $row['business_city_name'] = '其他';
            } else {
                $row['business_city_name'] = $addr->get_name_by_code($row['business_city']);
            }
        } else {
            $row['business_city_name'] = '未指定';
        }
        $row['manager_name'] = $row['manager_id'] > 0 ? $row['manager_name'] : '未分配';
        $row['three_in_one'] = $row['is_three_in_one'] == 1 ? '是' : '否';
        return $row;
    }


    /**
     * 短信设置详细
     * 返回短信设置详细信息
     *
     * @return   Object
     */
    public function mob_msgset_detail()
    {
        $detail = $this->dealer_base_info();
        $types = array(
            'start_au_remind' => ''
        , 'trading_remind' => ''
        , 'arbitrate_remind' => ''
        , 'money_change_remind' => ''
        );
        $types = array_intersect_key($detail, $types);
        return $types;
    }

    /**
     * 修改短信设置
     *
     * @param    int $msg_setting_tab 1.发起拍卖是否接收，2.交易提醒是否接收，3.仲裁提醒是否接收，4.充值保证金是否接收
     * @param    boolean $msg_setting_value 设置项值
     *
     * @return   boolean
     */
    public function change_mob_msgset($msg_setting_tab, $msg_setting_value)
    {
        $types = array(
            '1' => 'start_au_remind'
        , '2' => 'trading_remind'
        , '3' => 'arbitrate_remind'
        , '4' => 'money_change_remind'
        );
        $info = array();
        $info[$types[$msg_setting_tab]] = $msg_setting_value;
        $ok = $this->update($info);
        return $ok;
    }


    public function update($post_info, $user)
    {

        $dealer_id = $this->dealer_id;
        $info = $this->dealer_base_info();

        $dealer = M('car_dealer');
        $ok = $dealer->where(['dealer_id' => $this->dealer_id])->save($post_info);

        //更新用户信息
        if (!empty($user['passwd'])) {
            $user['passwd'] = md5($user['passwd']);
        } else {
            unset($user['passwd']);
        }
        $ok = M('user')->where('uid=\'' . $info['uid'] . '\'')->save($user);
        if ($info['manager_id'] != $post_info['manager_id']) {
            //TODO 更新客服经理
            $sql = "delete from " . C('DB_PREFIX') . "dealer_manager where emp_id='{$info['manager_id']}' and dealer_id='{$dealer_id}';";
            $ok = M()->execute($sql);
            $sql = "INSERT " . C('DB_PREFIX') . "dealer_manager SET emp_id='{$post_info['manager_id']}',dealer_id='{$dealer_id}';";
            $ok = M()->execute($sql);
        }
        if ($post_info['category'] == 1) {
            //更新提车人
            $tm = new TakeMan($this->dealer_id);
            $man_info = $tm->get_default_man();
            $data = array();
            $data['real_name'] = $post_info['contact_person'];
            $data['sex'] = $post_info['sex'];
            $data['mobile'] = $post_info['contact_mobile'];
            $data['idcard'] = $post_info['dealer_idcard'];
            if (empty($man_info)) {
                $data['take_num'] = 0;
                $data['is_contact_person'] = 1;
                $tm->add($data);
            } else {
                $data['man_id'] = $man_info['man_id'];
                $tm->edit($data);
            }
        }

        return $ok;
    }

    /**
     * 车商基本资料修改
     * @param array $data
     * @return bool
     */
    public function edit($data = array())
    {
        $ret = M('car_dealer')->where(array('dealer_id' => $this->dealer_id))->save($data);
        return $ret;
    }

    /**
     * 更新车商信息
     *
     * @param array $dealer_info
     * @param array $user
     * @param int $manager_id
     *
     * @return bool|false|int
     */
    public function update_dealer($dealer_info, $user, $manager_id)
    {

        $dealer_id = $this->dealer_id;
        $info = $this->dealer_base_info();

        //开启事务
        M()->startTrans();

        $dealer_res = M('car_dealer')->where(['dealer_id' => $this->dealer_id])->save($dealer_info);
        if ($dealer_res === false) {
            M()->rollback();
            return false;
        }
        $uc = new UserCenter();
        $user_res = $uc->changeUserInfo($user, 2);
        if (!$user_res) {
            M()->rollback();
            return false;
        }
        //更新客服经理
        if ($info['manager_id'] != $manager_id) {
            $find_m = M('dealer_manager')->where(['dealer_id' => $dealer_id])->getField('dealer_id');
            if ($find_m) {
                $dm_res = M('dealer_manager')->where(['dealer_id' => $dealer_id])->save(['emp_id' => $manager_id]);
            } else {
                $dm_res = M('dealer_manager')->add(['emp_id' => $manager_id, 'dealer_id' => $dealer_id]);
            }
            if (!$dm_res) {
                M()->rollback();
                return false;
            }
//            $dm_res1 = M('dealer_manager')->delete(['emp_id' => $info['manager_id'], 'dealer_id' => $dealer_id]);
//            $dm_res2 = M('dealer_manager')->add(['emp_id' => $dealer_info['manager_id'], 'dealer_id' => $dealer_id]);
//            if (!$dm_res1 && $dm_res2 < 1) {
//                M()->rollback();
//                return false;
//            }
        }
        M()->commit();
        return true;
    }


    /**查询车商的ID
     *
     * @param $info id、 车商名、车商手机号
     *              return int
     */
    public static function car_dealer_info($info)
    {
        $dealer = M('car_dealer');
        if (preg_match("/^1[34578]{1}\d{9}$/", $info)) {
            $sql = "contact_mobile=$info";
        }
        if (!is_numeric($info)) {
            $sql = "contact_person='$info'";
        }
        $id = $dealer->where($sql)->getField("dealer_id");
        return $id;
    }

    /**
     * 查询车商的名字
     *
     * @param string $dealer_name 车商姓名
     *                            return int $dealer_id
     */
    public function get_dealer_id_by_dealer_name($dealer_name)
    {
        $condition['user_name'] = $dealer_name;
        $info = M('user')->alias('u')->field('du.dealer_id')
            ->join(C('DB_PREFIX') . 'dealer_user as du ON u.uid = du.uid')
            ->where($condition)
            ->find();
        return $info['dealer_id'];
    }

    /**
     * 查询车商的名字
     *
     * @param string $dealer_id 车商id
     *                          return int $dealer_name
     */
    public function get_dealer_name_by_dealer_id($dealer_id)
    {
        $condition['cd.dealer_id'] = $dealer_id;
        $info = M('car_dealer')->alias('cd')->field('du.uid')
            ->join(C('DB_PREFIX') . "dealer_user as du ON du.dealer_id = cd.dealer_id")
            ->where($condition)->find();
        if (!empty($info)) {
            $uc = new UserCenter();
            $userInfo = $uc->info($info['uid'], 2);
            $info['user_name'] = $userInfo['account_name'];
            return $info['user_name'];
        }
    }

    /**
     * 查询车商的信息
     *
     * @param string $dealer_id 车商id
     * @return array $dealer_info
     */
    public static function get_dealer_info_by_dealer_id($dealer_id)
    {
        $condition['dealer_id'] = $dealer_id;
        $info = M('car_dealer')->where($condition)->find();
        return $info;
    }


    /**
     * 根据员工Id（客户经理编号） 获取 分公司Id
     *
     * @param $employee_id 员工编号（客户经理编号）
     *
     * @return mixed
     */
    public function get_branch_by_employee_id($employee_id)
    {
        $condition['e.emp_id'] = $employee_id;
        $info = M('employee')->alias('e')->field('d.branch_id')
            ->join(C('DB_PREFIX') . 'depart as d ON e.depart_id = d.id')
            ->where($condition)
            ->find();
        return $info;
    }

    //车商登录
    public static function login($user_name, $pwd)
    {
        /*if (is_numeric($user_name) && (strlen($user_name) == 11)) {
            $user_name = 'du' . $user_name;
        }*/
        $front_user = new \AuctionCore\Account\FrontUser($user_name);
        $info = $front_user->check_pwd($pwd);
        if ($info) {
            //检查账号是否被冻结
            if ($info['status'] == 1) {
                AuctionException::make_throw('500071');
            }
            //检查是否有车商中心权限
            $fu = new \AuctionCore\Account\FrontUser($info['user_name']);
            if (!$fu->check_auth("dealer_center")) {
                AuctionException::make_throw('500057');
            }

            //更新互斥登录
            $ul = new \AuctionCore\Account\UniqLogin();
            $uniq_login_token = $ul->update($info['uid']);
            $info['uniq_login_token'] = $uniq_login_token;
            //记入登录日志
            if (isset($info['uid']))
                \AuctionCore\Account\LoginLog::save($info['uid'], 0, sha1($uniq_login_token), get_client_ip());

            $info['dealer_id'] = self::uid_to_dealerid($info['uid']);
            $dealer = new Dealer($info['dealer_id']);
            $info['dealer_info'] = $dealer->dealer_base_info();
            unset($info['passwd']);
            unset($info['pwd_mobile']);
            unset($info['status']);
            return $info;
        }
        return false;
    }


    //不传密码，车商登录方式
    public static function loginByLoginKey($user_name, $login_key, $time)
    {
        try {
            $front_user = new \AuctionCore\Account\FrontUser($user_name);
            if (!$front_user->check_auth("dealer_center")) {
                AuctionException::make_throw('500057');
            }
            $info = $front_user->user_info();

            if ($info['status']) {
                AuctionException::make_throw('200010');
            }
            $pwd_md5 = $info['passwd'];
            if ($info && $login_key == sha1($user_name . $info['passwd'] . $time . C('auth')['salt'])) {

                $mem = new PhpMemcache();
                if ($mem->get('appapi_login_' . $login_key) || (time() - ($time / 1000)) > 30) {
                    AuctionException::make_throw('100068');
                }

                //更新互斥登录
                $ul = new \AuctionCore\Account\UniqLogin();
                $uniq_login_token = $ul->update($info['uid']);
                $info['uniq_login_token'] = $uniq_login_token;

                //车商信息
                $info['dealer_id'] = self::uid_to_dealerid($info['uid']);
                $dealer = new Dealer($info['dealer_id']);
                $info['dealer_info'] = $dealer->dealer_base_info();
                unset($info['passwd']);
                unset($info['pwd_mobile']);
                unset($info['status']);

                //记录登录请求key
                $mem->set('appapi_login_' . $login_key, $user_name, 40);
                return array($info, $pwd_md5);
            } else {
                AuctionException::make_throw('200022');
            }
        } catch (AuctionException $e) {
            if ($e->getCode() == '200008') {
                AuctionException::make_throw('200022');
            }
            AuctionException::make_throw($e->getCode());
        }
    }

    //uid转成车商id
    public static function uid_to_dealerid($uid)
    {
        if (is_numeric($uid)) {
            $r = M('dealer_user')->field('dealer_id')->where("uid='{$uid}'")->find();
            if ($r) {
                return $r['dealer_id'];
            }
        }
        return false;
    }

    //dealer_id转成uid
    public static function dealerid_to_uid($dealer_id)
    {
        if (is_numeric($dealer_id)) {
            $r = M('dealer_user')->field('uid')->where("dealer_id='{$dealer_id}'")->find();
            if ($r) {
                return $r['uid'];
            }
        }
        return false;
    }

    /**
     * 启用帐号
     *
     * @param array $user
     * @param int $dealer_id
     *
     * @return boolean
     */
    public static function enable_dealer_user($user, $dealer_id)
    {
        $emp_id = M('dealer_manager')->where(['dealer_id' => $dealer_id])->getField('emp_id');
        if ($emp_id <= 0) {
            AuctionException::make_throw('500013');
        }
        //开启事务
        M()->startTrans();
        $dealer_res = M('car_dealer')->where(['dealer_id' => $dealer_id])->setField('status', 1);
        $uc = new UserCenter();
        $uc_res = $uc->active($user, 2);
        if (!$dealer_res || !$uc_res) {
            M()->rollback();
            return false;
        }
        M()->commit();
        return true;
    }

    /**
     * 禁用帐号
     *
     * @param array $user
     * @param int $dealer_id
     *
     * @return  boolean
     */
    public static function disable_dealer_user($user, $dealer_id)
    {
        //踢出登录账号
        $redis = new PhpRedis(0);

        $keyArr = [
            'uid' => $user['account_id'],
        ];
        $lock_key = getRedisKeyByCode('REDIS_KEY','100014',$keyArr);
        //$redis->del("uniq_login_" . $user['account_id']);
        $redis->del($lock_key);
        //开启事务
        M()->startTrans();
        $dealer_res = M('car_dealer')->where(['dealer_id' => $dealer_id])->setField('status', 2);
        $uc = new UserCenter();
        $uc_res = $uc->inactive($user, 2);
        if (!$dealer_res || !$uc_res) {
            M()->rollback();
            return false;
        }
        M()->commit();
        return true;
    }

    /**
     * 重置密码
     *
     * @param $user
     *
     * @return boolean
     */
    public static function reset_pwd($user)
    {
        $uc = new UserCenter();
        return $uc->resetpwd($user, 2);
    }

    /**
     * 添加车商信息
     *
     *
     * @param info array
     *
     * @return   Object
     * @author Gran Ian
     */
    public static function create($info, $user)
    {
        if (!isset($info['status'])) {
            $info['status'] = 1;
        }
        //开启事务
        M()->startTrans();
        //添加车商
        $insertID = M('car_dealer')->add($info);
        //添加用户
        $uid = M('user')->add($user);
        //添加到车商组
        $ugd = M('auth_group_access')->add(array('uid' => $uid, 'group_id' => 2));
        //添加车商用户关联
        $ud = M('dealer_user')->add(array('uid' => $uid, 'dealer_id' => $insertID, 'status' => 1));
        //添加客服经理
        $dealer_manager = array('dealer_id' => $insertID, 'emp_id' => $info['manager_id']);
        $dm_id = M('dealer_manager')->add($dealer_manager);
        if ($info['category'] == 1) {
            //添加默认提车人
            $tm = new TakeMan($insertID);
            $data['real_name'] = $info['contact_person'];
            $data['sex'] = $info['sex'];
            $data['mobile'] = $info['contact_mobile'];
            $data['idcard'] = $info['dealer_idcard'];
            $data['take_num'] = 0;
            $data['is_contact_person'] = 1;
            $data['reg_date'] = date("Y-m-d H:i:s");
            $man_id = $tm->add($data);
        } else {
            $man_id = 1;
        }

        //出错回滚
        if ($insertID < 1 || $dm_id < 1 || $man_id < 1 || $uid < 1 || $ugd < 1 || $ud < 1) {
            M()->rollback();
            return false;
        }
        M()->commit();
        return $insertID;
    }

    /**
     * 添加车商用户信息 - 结合蚁巢服务平台
     *
     * @param $info array
     * @param $user array
     *
     * @return   Object
     * @author Xmh
     */
    public static function create_dealer($info, $user)
    {
        if (!isset($info['status'])) {
            $info['status'] = 1;
        }
        //开启事务
        M()->startTrans();
        //添加用户
        $uc = new UserCenter();
        $result = $uc->add($user, 2);
        $uid = $result['account_id'];
        $uc_createtime = $result['createtime'];
        //添加车商
        $info['createtime'] = $uc_createtime;
        $dealer_id = M('car_dealer')->add($info);
        //添加到车商组
        $ugd = M('auth_group_access')->add(
            [
                'uid' => $uid,
                'group_id' => 2
            ]
        );
        //添加车商用户关联
        $ud = M('dealer_user')->add(
            [
                'uid' => $uid,
                'dealer_id' => $dealer_id,
                'status' => 1
            ]
        );
        //添加客服经理
        $dm_id = M('dealer_manager')->add(
            [
                'dealer_id' => $dealer_id,
                'emp_id' => $info['man_id']
            ]
        );
        //出错回滚
        if ($dealer_id < 1 || $dm_id < 1 || $uid < 1 || $ugd < 1 || $ud < 1) {
            M()->rollback();
            return false;
        }
        M()->commit();
        return $dealer_id;
    }


    /**
     * 开通车商帐号
     * @param array $dealer
     * @param array $user
     * @return mixed
     */
    public static function open($dealer, $user)
    {
        if (!isset($dealer['status'])) {
            $dealer['status'] = 1;
        }
        //开启事务
        M()->startTrans();
        //添加车商
        $insertID = M('car_dealer')->add($dealer);
        //更新用户
        $u = M('user')->save($user);
        //添加到车商组
        $ugd = M('auth_group_access')->add(array('uid' => $user['uid'], 'group_id' => 2));
        //添加车商用户关联
        $ud = M('dealer_user')->add(array('uid' => $user['uid'], 'dealer_id' => $insertID, 'status' => 1));
        //添加客服经理
        $dm_id = M('dealer_manager')->add(array('dealer_id' => $insertID, 'emp_id' => $dealer['manager_id']));
        //出错回滚
        if ($insertID < 1 || $u < 1 || $ugd < 1 || $ud < 1 || $dm_id < 1) {
            M()->rollback();
            return false;
        }
        M()->commit();
        return $insertID;
    }


    /**
     * 删除车商
     *
     * @param unknown $dealer_id
     *
     * @return \Think\mixed
     */
    public static function remove($dealer_id)
    {
        $dealer = M('car_dealer');
        $ok = $dealer->where('dealer_id=\'' . $dealer_id . '\'')->delete();
        return $ok;
    }

    /**
     * 获取我的最高出价
     *
     * @param int $order_id 拍单ID
     *
     * @return array
     * */
    public function get_my_highest_price($order_id)
    {
        $price1 = M('bid_log')->where("order_id='" . $order_id . "' and dealer_id='" . $this->dealer_id . "'")->order("createtime DESC")->limit('0,1')->getField('price');
        $price2 = M('bidding_log')->where("order_id='" . $order_id . "' and dealer_id='" . $this->dealer_id . "'")->order("createtime DESC")->limit('0,1')->getField('after_price');
        if ($price2 > $price1) {
            $ret = array('bidding', $price2);
        } else {
            $ret = array('bid', $price1);
        }
        return $ret;
    }

    /**
     * 获取我的客户经理
     *
     * */
    public function my_manager()
    {
        return M('dealer_manager')->alias('dm')->field('e.*')->join(C('DB_PREFIX') . "employee e ON dm.emp_id=e.emp_id")->where("dm.dealer_id='" . $this->dealer_id . "'")->find();
    }


    public static function is_manager($group_id, $emp_id)
    {
        $map = array();
        $map['ega.id'] = array('eq', $group_id);
        $map['ega.emp_id'] = array('eq', $emp_id);
        return M('emp_group_access')->alias('ega')->field("e.emp_id,e.real_name")->join(C('DB_PREFIX') . "employee e ON ega.emp_id=e.emp_id")->where($map)->select();
    }

    /**
     * 获取指定分公司下所有客户经理信息
     *
     * */
    public static function get_dealer_by_branch($map)
    {

        return M('employee')->alias('e')->field("e.real_name,e.emp_id")
            ->join(C("DB_PREFIX") . "depart d ON d.id = e.depart_id ")
            ->join(C("DB_PREFIX") . "dealer_manager dm on dm.emp_id = e.emp_id")->where($map)->group('e.emp_id')->select();
    }

    /**
     *是否关注拍品
     * */
    public function is_followed($order_id)
    {
        return M('dealer_follow')->where("dealer_id='" . $this->dealer_id . "' AND order_id='" . $order_id . "'")->find();

    }

    /**
     * 我参与的拍品
     *
     * @return array order_id 拍单ID
     * */
    public function my_joined_auction()
    {
        //获取今明两天内车商参与的拍品拍单ID
        $sql = "select distinct(o.order_id) order_id from " . C("DB_PREFIX") . "order o
                            INNER JOIN " . C("DB_PREFIX") . "order_scene os ON os.scene_id=o.scene_id
                            WHERE o.status in(3,301,4) AND os.status in(1,2) AND o.order_id in(
                            SELECT order_id FROM " . C("DB_PREFIX") . "bid_log WHERE dealer_id='" . $this->dealer_id . "' AND createtime BETWEEN '" . date('Y-m-d 00:00:00', strtotime('-1 day')) . "' AND '" . date('Y-m-d 23:59:59', strtotime('+1 day')) . "'
                            UNION
                            SELECT order_id FROM " . C("DB_PREFIX") . "bidding_log WHERE dealer_id='" . $this->dealer_id . "' AND createtime BETWEEN '" . date('Y-m-d 00:00:00', strtotime('-1 day')) . "' AND '" . date('Y-m-d 23:59:59', strtotime('+1 day')) . "'
                            )";
        $res = M()->query($sql);
        $arr = array();
        foreach ($res as $v) {
            $arr[] = $v['order_id'];
        }
        return $arr;
    }

    /**
     * 我参与的拍品统计
     *
     * */
    public function stat_joined_auction()
    {
        //只统计今天明天参与的拍品
        $list = $this->my_joined_auction();
        return count($list);
    }

    /**
     * 我关注的拍品
     *
     */
    public function my_followed_auction()
    {
        //只统计今天明天参与的拍品，竞标结束就不再关注
        $map = array();
        $map['df.dealer_id'] = $this->dealer_id;
        $map['os.starttime'] = array(array('gt', date('Y-m-d 00:00:00', strtotime('-1 day'))), array('lt', date('Y-m-d 23:59:59', strtotime('+1 day'))));
        $map['o.status'] = array('in', '3,4,301');
        $map['os.status'] = array('in', '1,2');//场次状态 -1禁用 1待拍 2拍卖中 3 完成

        $res = M('order')->alias('o')->field("o.order_id")->join(C("DB_PREFIX") . "order_scene os on os.scene_id=o.scene_id")
            ->join(C("DB_PREFIX") . "dealer_follow df ON df.order_id=o.order_id")->where($map)->select();
        $arr = array();
        foreach ($res as $v) {
            $arr[] = $v['order_id'];
        }
        return $arr;
    }

    /**
     * 我关注的拍品统计
     *
     * */
    public function stat_followed_auction()
    {
        $list = $this->my_followed_auction();
        return count($list);
    }

    /**
     * 检查是否关注
     *
     * @param $order_id
     *
     * @return bool|mixed
     */
    public function is_follow($order_id)
    {
        if (empty($order_id)) {
            return false;
        }
        $map = array(
            'dealer_id' => $this->dealer_id,
            'order_id' => $order_id
        );
        return M('dealer_follow')->where($map)->find();
    }

    /**
     * 添加关注
     */
    public function add_follow($order_id)
    {
        $data = array();
        $data['dealer_id'] = $this->dealer_id;
        $data['order_id'] = $order_id;
        $c = M('dealer_follow')->where("dealer_id='" . $this->dealer_id . "' and order_id='" . $order_id . "'")->find();
        if (!empty($c)) {
            AuctionException::make_throw('500060');
        }
        if (!$data['dealer_id'] || !$data['order_id']) {
            AuctionException::make_throw('500058');
        }
        return M('dealer_follow')->add($data);
    }

    /**
     * 取消关注
     */
    public function remove_follow($order_id)
    {
        $data = array();
        $data['dealer_id'] = $this->dealer_id;
        $data['order_id'] = $order_id;
        if (!$data['dealer_id'] || !$data['order_id']) {
            AuctionException::make_throw('500059');
        }

        return M('dealer_follow')->where("dealer_id='" . $this->dealer_id . "' and order_id='" . $order_id . "'")->delete();
    }

    /**
     * 车商确认跟踪记录
     *
     * @param array $data 数据
     *
     */
    public function confirm_trace_log($data = array())
    {
        if (empty($data['order_id'])) {
            AuctionException::make_throw('700027');
        }

        $data['dealer_id'] = $this->dealer_id;
        $data['createtime'] = date('Y-m-d H:i:s');
        return M('dealer_confirm_log')->add($data);
    }

    public function detail()
    {
        $map['cd.dealer_id'] = array('eq', $this->dealer_id);
        return M('car_dealer')->alias('cd')->field('cd.*,du.uid')->where($map)
            ->join(C('DB_PREFIX') . "dealer_user as du ON cd.dealer_id=du.dealer_id")
            ->find();
    }

    /**
     * 更新车商
     *
     * @param array $info 要更新的信息
     * @param array $map 条件
     *
     * @return boolean
     */
    public function updateDealer($info, $map = array())
    {
        if (empty($map)) {
            $map['dealer_id'] = array('eq', $this->dealer_id);
        }
        return M('car_dealer')->where($map)->save($info);
    }

    /**
     * 通过order_id,dealer_id获取车商冻结保证及解冻金额
     *
     * @param int $dealer_id
     * @param int $order_id
     *
     * @return \Think\mixed
     */
    public static function getBailAmountByOrder($dealer_id, $order_id)
    {
        $cond = array(
            'dealer_id' => $dealer_id,
            'order_id' => $order_id,
            'use_type' => 3, // 保证金应用类型 1充值 2冻结出价保证金 3解冻出价保证金 4提取 5争议支出 6违约赔付 7其它
        );
        return M('dealer_bail_log')->where($cond)->find();
    }

    /**
     * 通过id获取车商信息
     *
     * @param int $dealer_id
     *
     * @return \Think\mixed
     */
    public static function getDealerById($dealer_id)
    {
        $map['cd.dealer_id'] = array('eq', $dealer_id);
        return M('car_dealer')->alias('cd')->field('cd.*,du.uid')->where($map)
            ->join(C('DB_PREFIX') . "dealer_user as du ON cd.dealer_id=du.dealer_id")
            ->find();
    }

    /**
     * 通过id获取车商信息
     *
     * @param int $dealer_id
     *
     * @return \Think\mixed
     */
    public static function getDealerInfoById($dealer_id)
    {
        if ($dealer_id < 1) {
            return false;
        }
        $map['cd.dealer_id'] = ['eq', $dealer_id];
        return M('car_dealer')->alias('cd')->field('du.uid,u.real_name as contact_person')
            ->join(C('DB_PREFIX') . "dealer_user as du ON cd.dealer_id=du.dealer_id")
            ->join(C('DB_PREFIX') . "user as u ON  du.uid=u.uid")
            ->where($map)
            ->find();
    }

    /**
     * 获取提车人
     *
     * @param int $dealer_id
     */
    public static function getTakeCarMan($dealer_id)
    {
        $map = array();
        $map['dealer_id'] = array('eq', $dealer_id);
        return M('take_car_man')->where($map)->select();
    }

    /**
     * 更新车商基本信息
     *
     * @param unknown $data
     *
     * @return Ambigous <boolean, unknown>
     */
    public function updateDealerInfo($data)
    {
        $dealer = M('car_dealer');
        $map = array('dealer_id' => array('eq', $this->dealer_id));
        return $dealer->where($map)->save($data);
    }

    /**
     * 更新车商头像
     *
     * @param type $data
     *
     * @return type
     */
    public function updateDealerHead($data)
    {
        $dealer = M('user');
        $map = array('dealer_id' => array('eq', $this->dealer_id));
        $uid = M('dealer_user')->where($map)->getField('uid');
        return $dealer->where(array('uid' => $uid))->save($data);
    }

    /**
     *获取分配给我的代金券
     */
    public function get_my_coupon()
    {
        $map = array();
        $map['dealer_id'] = array('eq', $this->dealer_id);
        $map['use_status'] = array('eq', '0');
        $res = M('dealer_coupon')->where($map)->select();
        //echo M()->getLastSql();
        return $res;
    }

    /**
     * 使用代金卷
     */
    public function do_cost_coupon($data)
    {
        $arr = array();
        //dealer_id order_id cost_type occur_time occur_money remark createtime  dealer_confirm_status
        $dealer_id = $data['dealer_id'];
        $order_id = $data['order_id'];

        //事务开始
        M()->startTrans();

        foreach ($data['coupon_ids'] as $coupon_id) {

            $coupon = M('coupon')->alias('c')->field("ct.type_name,ct.amount,c.coupon_id")->join(C('DB_PREFIX') . "coupon_type ct ON ct.coupon_type_id=c.coupon_type_id")
                ->where("c.coupon_id='" . $coupon_id . "'")->find();
            $info = array();
            $info['dealer_id'] = $dealer_id;
            $info['cost_type'] = $coupon['type_name'];
            $info['occur_money'] = $coupon['amount'];//代金卷面额
            $info['order_id'] = $order_id;
            $info['coupon_id'] = $coupon_id;
            $info['coupon_no'] = $coupon['coupon_no'];
            $info['occur_type'] = 1;
            $res = CouponLog::add($info);

            $arr[] = $res;
            //更新使用状态
            //$res1 = M('coupon')->where("coupon_id='" . $coupon['coupon_id'] . "'")->save(array('use_status' => '1'));
            //$arr[] = $res1;
            $res2 = M('dealer_coupon')->where("dealer_id='" . $dealer_id . "' AND coupon_id='" . $coupon_id . "'")->save(array('use_status' => '1'));
            $arr[] = $res2;
            if (!$res || !$res2) {
                $log = array('order_id' => $order_id, 'dealer_id' => $dealer_id, 'action' => '车商代金券消耗失败，发生金额:' . $data['amount'] . '');
                \AuctionCore\System\SystemLog::add($log);
            }
        }

        if (in_array(false, $arr)) {
            M()->rollback();
            return false;
        } else {
            M()->commit();
            return true;
        }

    }

    /**
     * 获取我最的投标价
     * */
    public function get_my_last_bid_price($order_id)
    {
        return M('bid_log')->where("order_id='" . $order_id . "' AND dealer_id='" . $this->dealer_id . "'")->order('createtime desc')->limit("0,1")->getField('price');
    }

    /**
     * 设置客服经理
     */
    public function set_dealer_mannager($mannager_id)
    {
        $data = array(
            'dealer_id' => $this->dealer_id,
            'emp_id' => $mannager_id
        );
        return M('dealer_manager')->add();
    }

    /**
     * 更新客服经理
     */
    public function update_dealer_mannager($mannager_id)
    {
        $data = array(
            'emp_id' => $mannager_id
        );
        return M('dealer_manager')->where("dealer_id='{$this->dealer_id}'")->save($data);
    }


    //清除保证金缓存
    public static function clear_dealer_bail_cache($dealer_id)
    {
        //清空保证金缓存
        $mem = new \AuctionCore\Common\PhpMemcache();
        $mem->rm('dealer_info_' . $dealer_id);
    }


    // 通过order_id 找到对应的车商id
    public static function get_dealer_by_order_id($order_id)
    {
        $order = new AuOrder($order_id);
        $orderInfo =$order->detail();
        if (empty($orderInfo)){
            return false;
        }
        return array(['dealer_id'=>$orderInfo['success_dealer_id']]);
    }


    /**
     * 获取车商合同信息
     *
     */
    public function get_dealer_contract()
    {
        if (empty($this->dealer_id)) {
            return false;
        }
        $condition['cd.dealer_id'] = ['eq', $this->dealer_id];
        //要查询的列表
        $cols = 'cd.dealer_id,cd.sign_contract_no,cd.fullname,cd.organization_code,cd.contact_person,cd.dealer_idcard,
                du.uid,cd.province,cd.city,cd.area,cd.address,cd.sign_time,cd.auth_type,cd.auth_status,u.real_name,u.reg_date';
        $prefix = C('DB_PREFIX');
        $res = M('car_dealer')->alias('cd')->field($cols)
            ->join($prefix . "dealer_user as du ON du.dealer_id = cd.dealer_id")
            ->join($prefix . "user as u ON u.uid = du.uid")
            ->where($condition)->find();
        $res = $this->get_contact_mobile_byAntNestfind($res);
        $this->Addr = new Address();
        $res['dealer_address'] = $this->Addr->get_full_name($res['area']) . $res['address'];
        $res['dealer_name'] = $res['real_name'];
        $sign_start_time = strtotime($res['sign_time']);
        $sign_end_time = strtotime($res['sign_time']) + 60 * 60 * 24 * 365;
        $res['sign_start_time'] = date("Y-m-d", $sign_start_time);
        $res['sign_start_time_y'] = date("Y", $sign_start_time);
        $res['sign_start_time_m'] = date("m", $sign_start_time);
        $res['sign_start_time_d'] = date("d", $sign_start_time);
        $res['sign_end_time_y'] = date("Y", $sign_end_time);
        $res['sign_end_time_m'] = date("m", $sign_end_time);
        $res['sign_end_time_d'] = date("d", $sign_end_time);
        return $res;
    }

    /**
     * 通过dealerId 获取车商uid
     * @param $dealer_id
     * @return bool|mixed
     */
    public static function getUidByDealerId($dealer_id)
    {
        if ($dealer_id < 1) return false;
        return M("dealer_user")->where(['dealer_id' => $dealer_id])->getField("uid");
    }

    //从蚁巢批量获取contact_mobile处理列表数组的方法
    public function get_contact_mobile_byAntNest($list)
    {
        $uc = new UserCenter();
        $uids = array();
        foreach ($list as $key => $val) {
            $uids[] = $val['uid'];
        }
        $uniqueuids = array_unique($uids);
        $userCount = count($uniqueuids);
        if($userCount > 100){
            $num = ceil($userCount / 100);
            for($i = 1;$i<= $num; $i++){
                $userArr = array_slice($uniqueuids,($i - 1) * 100 ,100);
                $uc = new UserCenter();
                $userinfo = $uc->batchInfo($userArr, 2);
                foreach ($userinfo['list'] as $key => $val) {
                    foreach ($list as $k => $v) {
                        if ($val['account_id'] == $v['uid']) {
                            $list[$k]['contact_mobile'] = $val['mobile'];
                        }
                    }
                }
            }
        }else{
            $userinfo = $uc->batchInfo($uniqueuids, 2);
            foreach ($userinfo['list'] as $key => $val) {
                foreach ($list as $k => $v) {
                    if ($val['account_id'] == $v['uid']) {
                        $list[$k]['contact_mobile'] = $val['mobile'];
                    }
                }
            }
        }

        return $list;
    }

    //从蚁巢获取contact_mobile方法
    public function get_contact_mobile_byAntNestfind($list)
    {
        $uc = new UserCenter();
        $userinfo = $uc->getInfo($list['uid'], 2);
        $list['contact_mobile'] = $userinfo['mobile'];
        return $list;
    }
}
